﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace GraphicsFramework.Drawing.Primitive
{
    public class Circle : BasePrimitive
    {

        private float radius;
        private int segments;

        public Circle()
            : base(Enum.EnumDrawingType.POLYGON, "Draw Circle", Enum.EnumMouseClicks.TWO)
        {
            Initialize(0, 0, 0);
        }

        public Circle(float x, float y, float radius)
            : base(Enum.EnumDrawingType.POLYGON, "Draw Circle", Enum.EnumMouseClicks.TWO)
        {
            Initialize(x, y, radius);
        }

        public Circle(Entity.Point2F point, float radius)
            : base(Enum.EnumDrawingType.POLYGON, "Draw Circle", Enum.EnumMouseClicks.TWO)
        {
            Initialize(point.X, point.Y, radius);
        }

        private void Initialize(float x, float y, float radius)
        {
            segments = 16;
            this.radius = radius;
            Center = new Entity.Point2F(x, y);

            properties = Property.DefaultProperty.Common;
            UpdatePoints();
        }

        private void UpdatePoints()
        {
            float theta = (float)(2 * Math.PI / segments);
            float tanfactor = (float)Math.Tan(theta);

            float radfactor = (float)Math.Cos(theta);
            float xvalue = radius;
            float yvalue = 0;

            float tempx;
            float tempy;

            points = new List<Entity.Point2F>();

            for (int i = 0; i < segments; i++)
            {
                points.Add(new Entity.Point2F(xvalue + Center.X, yvalue + Center.Y));

                tempx = -yvalue;
                tempy = xvalue;

                xvalue += tempx * tanfactor;
                yvalue += tempy * tanfactor;

                xvalue *= radfactor;
                yvalue *= radfactor;
            }

            //Update the drawing after adding points.
            UpdateDrawing();
        }

        public override GraphicBase Clone()
        {
            Circle graphic = new Circle(Center.X, Center.Y, radius);

            //Clone base properties
            base.Clone(graphic);

            return graphic;
        }
        
        public override void OnRender(GraphicsFramework graphics)
        {
            int seg = (int)(((graphics.Gridsize * radius) / 100) * 32);

            if (seg < 16)
                seg = 16;

            if (segments != seg)
            {
                segments = seg;
                UpdatePoints();
            }

            base.OnRender(graphics);
        }

        public override void UpdateGuide(List<Entity.Point2F> mousedown, Entity.Point2F mousemove)
        {
            Entity.Line2F line = new Entity.Line2F(mousedown[0], mousemove);
            Initialize(mousedown[0].X, mousedown[0].Y, line.GetLength());
        }

    }
}
